package com.search_wheel.service;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchHistoryService {

    private static final String SEARCH_HISTORY_KEY = "searchHistory";
    private static final int MAX_HISTORY_SIZE = 10; // 最多保存10条历史记录

    /**
     * 获取搜索历史记录
     */
    @SuppressWarnings("unchecked")
    public List<String> getSearchHistory(HttpSession session) {
        List<String> history = (List<String>) session.getAttribute(SEARCH_HISTORY_KEY);
        return history != null ? new ArrayList<>(history) : new ArrayList<>();
    }

    /**
     * 添加搜索历史记录
     */
    @SuppressWarnings("unchecked")
    public void addSearchHistory(HttpSession session, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return;
        }

        keyword = keyword.trim();
        List<String> history = (List<String>) session.getAttribute(SEARCH_HISTORY_KEY);

        if (history == null) {
            history = new ArrayList<>();
        } else {
            // 创建新的列表避免并发问题
            history = new ArrayList<>(history);
        }

        // 如果已存在，先移除（避免重复）
        history.remove(keyword);

        // 添加到列表开头
        history.add(0, keyword);

        // 限制历史记录数量
        if (history.size() > MAX_HISTORY_SIZE) {
            history = history.subList(0, MAX_HISTORY_SIZE);
        }

        session.setAttribute(SEARCH_HISTORY_KEY, history);
    }

    /**
     * 获取搜索建议（基于历史记录的模糊匹配）
     */
    public List<String> getSearchSuggestions(HttpSession session, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return new ArrayList<>();
        }

        List<String> history = getSearchHistory(session);
        String lowerKeyword = keyword.toLowerCase().trim();

        return history.stream()
                .filter(item -> item.toLowerCase().contains(lowerKeyword))
                .distinct()
                .limit(5) // 最多返回5个建议
                .collect(Collectors.toList());
    }

    /**
     * 清空搜索历史记录
     */
    public void clearSearchHistory(HttpSession session) {
        session.removeAttribute(SEARCH_HISTORY_KEY);
    }

    /**
     * 删除指定的搜索历史记录
     */
    @SuppressWarnings("unchecked")
    public void removeSearchHistory(HttpSession session, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return;
        }

        List<String> history = (List<String>) session.getAttribute(SEARCH_HISTORY_KEY);
        if (history != null) {
            history = new ArrayList<>(history);
            history.remove(keyword.trim());
            session.setAttribute(SEARCH_HISTORY_KEY, history);
        }
    }

    /**
     * 获取热门搜索词（示例方法，实际可能从数据库获取）
     */
    public List<String> getHotKeywords(String prefix) {
        // 这里可以从数据库或缓存中获取热门搜索词
        // 示例数据
        List<String> hotKeywords = Arrays.asList(
                "Java编程", "Spring Boot", "Vue.js", "微服务架构",
                "数据库设计", "算法学习", "前端开发", "后端开发"
        );

        if (prefix == null || prefix.trim().isEmpty()) {
            return hotKeywords.subList(0, Math.min(5, hotKeywords.size()));
        }

        String lowerPrefix = prefix.toLowerCase().trim();
        return hotKeywords.stream()
                .filter(keyword -> keyword.toLowerCase().contains(lowerPrefix))
                .limit(5)
                .collect(Collectors.toList());
    }
}